package com.sptci.rwt;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;

import java.util.ArrayList;
import java.util.Collection;

import com.sptci.util.CloseJDBCResources;

/**
 * An analyser for analysing table type objects in the database.
 *
 * <p>&copy; Copyright 2007 Sans Pareil Technologies, Inc.</p>
 * @author Rakesh Vidyadharan 2007-09-25
 * @version $Id: TableAnalyser.java 2 2007-10-19 21:06:36Z rakesh.vidyadharan $
 */
public class TableAnalyser extends Analyser
{
  /**
   * The <code>types</code> parameters to specify while invoking the
   * {@link java.sql.DatabaseMetaData#getTables} method.
   */
  private static final String[] TYPE = new String[] { "TABLE", "SYNONYM" };

  /**
   * Create a new instance of the class using the specified connection
   * manager.
   *
   * @param manager The manager for obtaining database connections.
   */
  public TableAnalyser( final ConnectionManager manager )
  {
    super( manager );
  }

  /**
   * Returns a collection of {@link TableMetaData} objects that contain the
   * basic information pertaining to the tables in the schema.
   *
   * @see Analyser#analyse
   * @param parameters Must contain one parameter which is a {@link
   *   SchemaMetaData} that represents the
   *   <code>schema</code> to restrict the analysis to.  The name of the
   *   <code>schema</code> may be <code>null</code> or an empty string.
   *   See {@link java.sql.DatabaseMetaData#getTables} for a description
   *   of the behaviour of specifying the schema.
   */
  @Override
  public Collection<TableMetaData> analyse( final MetaData... parameters )
    throws SQLException
  {
    Collection<TableMetaData> collection = new ArrayList<TableMetaData>();
    Connection connection = null;
    ResultSet resultSet = null;

    try
    {
      String schema = ( parameters[0] == null ) ? null : parameters[0].getName();
      connection = manager.open();
      DatabaseMetaData dmd = connection.getMetaData();
      resultSet = dmd.getTables( null, schema, "%", TYPE );

      while ( resultSet.next() )
      {
        TableMetaData tmd = new TableMetaData();

        tmd.setName( resultSet.getString( "table_name" ) );
        tmd.setComment( resultSet.getString( "remarks" ) );
        if ( parameters[0] != null )
        {
          tmd.setSchema( (SchemaMetaData) parameters[0] );
        }

        collection.add( tmd );
      }

      if ( parameters[0] != null )
      {
        ( (SchemaMetaData) parameters[0] ).setTables( collection );
      }
    }
    finally
    {
      CloseJDBCResources.close( resultSet );
      CloseJDBCResources.close( connection );
    }

    return collection;
  }
}
